<template>
  <el-menu background-color="var(--xz-bg-color)" :collapse="isCollapse" :router="true" :default-active="defaultActive"
    :default-openeds="['cluster']" @select="handleSelect" class="guardcat-menu">
    <div v-for="menu in finalMenu" :key="menu.routeName">
      <!-- 没有子菜单的菜单 -->
      <el-menu-item v-if="menu.children == null || menu.children.length === 0" :index="menu.routeName">
        <el-icon :class="menu.icon"></el-icon>
        <template #title>{{ menu.menuName }}</template>
      </el-menu-item>

      <!-- 有子菜单的菜单 -->
      <el-sub-menu v-else :index="menu.routeName">
        <template #title>
          <el-icon :class="menu.icon"></el-icon>
          <span>
            {{ menu.menuName }}
          </span>
        </template>

        <el-menu-item v-for="child in menu.children" :index="child.routeName" :key="child.routeName">
          <el-icon :class="child.icon"></el-icon>
          <template #title>
            <el-badge v-if="child.tags.length > 0" el-badge :value="child.tags" type="primary">
              {{ child.menuName }}
            </el-badge>
            <span v-else>
              {{ child.menuName }}
            </span>
          </template>
        </el-menu-item>
      </el-sub-menu>
    </div>
  </el-menu>
</template>

<script setup lang="ts">
import router from '@/router';
import { ref, watch, onMounted } from 'vue';
import { storeToRefs } from 'pinia';
import { asideMenuConstant } from '@/assets/constants/menu';
import { menuTreeByAuthUserApi } from '@/api/rbac';
import { useAuthStore } from '@/stores/auth';
import { isNotNull } from '@/assets/utils/obj';

const authStore = useAuthStore();
const { auth } = storeToRefs(authStore);

const isCollapse = ref(false);
const defaultActive = ref('home');
// 监听路由并选中菜单
watch(() => router.currentRoute.value, (newRoute: any, oldRoute: any) => {
  if (isNotNull(newRoute) && isNotNull(newRoute.path)) {
    defaultActive.value = newRoute.path.substring(1);
  }
})

const handleSelect = (key: string, keyPath: string[]) => {
  // 路由跳转
  // router.push(key)
}

const finalMenu = ref<any>([]);

const getMenuTreeByAuthUserApi = () => {
  initMenu();
  menuTreeByAuthUserApi().then((resp: any) => {
    resp.data?.forEach((menu: any) => {
      finalMenu.value.push(menu);
    });
  })
}

const initMenu = () => {
  finalMenu.value = [];
  asideMenuConstant.forEach((menu: any) => {
    finalMenu.value.push(menu)
  })
}

onMounted(() => {
  if (auth.value.statu === 'SUCC') {
    // getMenuTreeByAuthUserApi();
    initMenu();
  } else {
    initMenu();
  }
})
</script>

<style scoped lang="scss">
.guardcat-menu {
  --el-menu-item-height: 36px;
  --el-menu-sub-item-height: 36px;
  --el-menu-text-color: #86888e;
}

.el-menu {
  height: 100%;
  overflow-y: scroll;
  border: 0;
  font-weight: 700;


  :deep(.el-badge__content) {
    top: 7px;
    transform: translateY(-50%) translateX(100%) scale(0.8);
  }
}
</style>